﻿using System;
using System.Collections.Generic;
namespace Common
{
	public class EventTools
	{
		private static EventTools eventtools = new EventTools();
		private Dictionary<string, List<Action>> event_mapping = new Dictionary<string, List<Action>>();
		private List<KeyValuePair<string, Action>> event_new_list = new List<KeyValuePair<string, Action>>();

		private EventTools() {}

		/// <summary>
		/// 获取单例
		/// </summary>
		/// <returns>The instance.</returns>
		public static EventTools GetInstance()
		{
			return eventtools;
		}

		/// <summary>
		/// 添加回调
		/// </summary>
		/// <param name="name">Name.</param>
		/// <param name="func">Func.</param>
		public void AddCallback(string name, Action func)
		{
			lock (event_new_list)
			{
				event_new_list.Add(new KeyValuePair<string, Action>(name, func));
			}
		}

		/// <summary>
		/// 触发事件
		/// </summary>
		/// <param name="name">Name.</param>
		public void TriggerEvent(string name) 
		{
			Console.WriteLine("TriggerEvent " + name);

			lock (event_new_list)
			{
				foreach (var item in event_new_list)
				{
					if (!event_mapping.ContainsKey(item.Key))
					{
						event_mapping.Add(item.Key, new List<Action>());
					}

					event_mapping[item.Key].Add(item.Value);	
				}

				event_new_list.Clear();
			}

			if (event_mapping.ContainsKey(name)) 
			{
				foreach (var item in event_mapping[name])
				{
					item();
				}
			}
		}
	}
}
